<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>个人中心</title>
    <meta charset="utf-8">
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <base href="http://localhost/campus/">
    <link rel="shortcut icon" href="static/favicon.ico" type="image/x-icon"/>
    <link rel="stylesheet" type="text/css" href="layui/css/layui.css"/>
    <link rel="stylesheet" type="text/css" href="static/css/person.css"/>
    <script src="static/js/jquery.min.js"></script>
    <script src="static/js/jquery.qrcode.min.js"></script>
    <script src="layui/layui.js" charset="utf-8"></script>
</head>
<body>
<div class="layui-fluid">
    <jsp:include page="/pages/common/header.jsp"/>

    <%--主体内容--%>
    <div class="layui-row center">
        <div class="layui-col-xs2 layui-col-sm2 layui-col-md2">
            <div class="center_category">
                <ul class="layui-nav layui-nav-tree layui-inline" lay-shrink="all" style="background: #797979;">
                    <li class="layui-nav-item">
                        <a href="person/update" style="background: #797979;">修改信息</a>
                    </li>
                    <li class="layui-nav-item">
                        <a href="person/myRelease?curPage=1" style="background: #797979;">我的发布</a>
                    </li>
                    <li class="layui-nav-item">
                        <a href="person/myFavorite" style="background: #797979;">我的收藏</a>
                    </li>
                    <li class="layui-nav-item layui-this">
                        <a href="javascript:;" style="background: #797979;">我的订单</a>
                    </li>
                </ul>
            </div>
        </div>
        <div class="layui-col-xs10 layui-col-sm10 layui-col-md10">
            <div class="order_body" style="display: block;">
                <div class="layui-tab layui-tab-card">
                    <ul class="layui-tab-title">
                        <li class="layui-this">我买的</li>
                        <li>我卖的</li>
                    </ul>
                    <div class="layui-tab-content" style="height: 100px;">
                        <div class="layui-tab-item layui-show">
                            <div id="table_purchase"></div>
                        </div>
                        <div class="layui-tab-item">
                            <div id="table_sell"></div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <%@include file="/pages/common/footer.jsp" %>
    <div id="orderDetailView" style="display:none;"></div>
    <div id="qrcodeDiv" style="display: none;width: 100%;text-align: center">
        <div id="qrcode"></div>
        <p id="qrcode_warning" style="color: darkblue;font-size: 18px;text-align: center;line-height: 42px;">请用微信扫一扫</p>
    </div>
</div>
<script type="text/html" id="purchaseOperationTpl">
    <div>
        <button class="layui-btn layui-btn-sm layui-btn-normal" onclick="orderDetail({{= JSON.stringify(d)}},true)">查看详情
        </button>
    </div>
</script>
<script type="text/html" id="sellOperationTpl">
    <div>
        <button class="layui-btn layui-btn-sm layui-btn-normal" onclick="orderDetail({{= JSON.stringify(d)}},false)">
            查看详情
        </button>
    </div>
</script>
<script type="text/html" id="purchaseOrderStateTpl">
    {{#  if(d.orderState == 0 ){ }}
    <p style="color: #fca130;">待付款</p>
    {{#  } else if(d.orderState == 1 ) { }}
    <p style="color:darkorange;">待卖家发货</p>
    {{#  } else if(d.orderState == 2 ) { }}
    <p style="color: green;">发货中</p>
    {{#  } else {}}
    <p style="color: dodgerblue;">订单完成</p>
    {{# }}}
</script>
<script type="text/html" id="sellOrderStateTpl">
    {{#  if(d.orderState == 0 ){ }}
    <p style="color: #fca130;">等待买家付款</p>
    {{#  } else if(d.orderState == 1 ) { }}
    <p style="color: darkorange;">待发货</p>
    {{#  } else if(d.orderState == 2 ) { }}
    <p style="color: green;">已发货</p>
    {{#  } else {}}
    <p style="color: dodgerblue;">订单完成</p>
    {{# }}}
</script>
<script id="purchaseOrderItemTpl" type="text/html">
    <div class="order_info_nav">订单详情</div>
    <div style="width: 100%;display: flex;">
        <div class="order_detail_item" style="width: 18%">
            <label>订单号：</label>
            <label>状态：</label>
            <label>总价格：</label>
            <label>支付方式：</label>
            <label>下单时间：</label>
            <label>收件人：</label>
            <label>联系电话：</label>
            <label>地址：</label>
        </div>
        <div class="order_detail_item" style="padding-left: 0;">
            <span>{{d.orderId}}</span>
            {{# if(d.orderState == 0 ){ }}
            <span style="color: #fca130;">待付款</span>
            {{# } else if(d.orderState == 1 ) { }}
            <span style="color:darkorange;">待卖家发货</span>
            {{# } else if(d.orderState == 2 ) { }}
            <span style="color: green;">发货中</span>
            {{# } else {}}
            <span style="color: dodgerblue;">订单完成</span>
            {{# }}}
            <span style="color: red">{{d.totalPrice}}</span>
            {{# if(d.orderList[0].purchaseWay == 0 ){ }}
            <span>支付宝</span>
            {{# } else if(d.orderList[0].purchaseWay == 1 ) { }}
            <span>微信</span>
            {{# } else {}}
            <span>其他</span>
            {{# }}}
            <span style="color: #007DDB">{{d.purchaseTime}}</span>
            <span>{{d.userName}}</span>
            <span>{{d.phone}}</span>
            <span>{{d.address}}</span>
        </div>
    </div>

    <div class="order_info_nav">商品详情</div>
    <div style="width: 100%;height: 110px;overflow-y: auto">
        {{# for(let i = 0; i < d.orderList.length; i++){ }}
        <div class="personRelease_item" style="width: 46%;height: 72px;margin: 6px;font-size: 13px;float: left">
            <img alt="" src="{{d.orderList[i].productImg}}" style="width: 45px;height: 45px;margin: 12px 6px;">
            <div class="order_product_detail_item">
                <span>{{d.orderList[i].productName}}</span>
                <span style="color:red;">单价:{{d.orderList[i].price}}</span>
                <span style="color: #1E9FFF">卖家:{{d.orderList[i].releaseUserPojo.realName}}</span>
            </div>
        </div>
        {{# } }}
    </div>

    <div style="width: 100%;height: 60px">
        {{# if(d.orderState == 0 ){ }}
        <button class="layui-btn layui-btn-sm layui-btn-danger" style="float: right;margin: 6px 10px;"
                onclick="deleteOrder('{{d.orderId}}',1)">取消订单
        </button>
        <button class="layui-btn layui-btn-sm layui-btn-warm"
                onclick="paySuccess('{{d.orderId}}','{{d.orderList[0].purchaseWay}}','{{d.orderList[0].qrcodeUrl}}')"
                style="float: right;margin: 6px 10px;">继续付款
        </button>
        {{# } else if(d.orderState == 1 ) { }}
        {{# } else if(d.orderState == 2 ) { }}
        <button class="layui-btn layui-btn-sm layui-btn-normal" style="float: right;margin: 6px 10px;"
                onclick="sendProduct('{{d.orderId}}',false)">确认收货
        </button>
        {{# } else {}}
        {{# }}}
    </div>
</script>
<script id="sellOrderItemTpl" type="text/html">
    <div class="order_info_nav">订单详情</div>
    <div style="width: 100%;display: flex;">
        <div class="order_detail_item" style="width: 18%">
            <label>订单号：</label>
            <label>状态：</label>
            <label>总价格：</label>
            <label>支付方式：</label>
            <label>下单时间：</label>
            <label>购买人：</label>
            <label>联系电话：</label>
            <label>地址：</label>
        </div>
        <div class="order_detail_item" style="padding-left: 0;">
            <span>{{d.orderId}}</span>
            {{# if(d.orderState == 0 ){ }}
            <span style="color: #fca130;">等待买家付款</span>
            {{# } else if(d.orderState == 1 ) { }}
            <span style="color: darkorange;">待发货</span>
            {{# } else if(d.orderState == 2 ) { }}
            <span style="color: green;">已发货</span>
            {{# } else {}}
            <span style="color: dodgerblue;">订单完成</span>
            {{# }}}
            <span style="color: red">{{d.totalPrice}}</span>
            {{# if(d.orderList[0].purchaseWay == 0 ){ }}
            <span>支付宝</span>
            {{# } else if(d.orderList[0].purchaseWay == 1 ) { }}
            <span>微信</span>
            {{# } else {}}
            <span>其他</span>
            {{# }}}
            <span style="color: #007DDB">{{d.purchaseTime}}</span>
            <span>{{d.userName}}</span>
            <span>{{d.phone}}</span>
            <span>{{d.address}}</span>
        </div>
    </div>

    <div class="order_info_nav">商品详情</div>
    <div style="width: 100%;height: 110px;overflow-y: auto">
        {{# for(let i = 0; i < d.orderList.length; i++){ }}
        <div class="personRelease_item" style="width: 46%;height: 72px;margin: 6px;font-size: 13px;float: left">
            <img alt="" src="{{d.orderList[i].productImg}}" style="width: 45px;height: 45px;margin: 12px 6px;">
            <div class="order_product_detail_item">
                <span>{{d.orderList[i].productName}}</span>
                <span style="color:red;">单价:{{d.orderList[i].price}}</span>
            </div>
        </div>
        {{# } }}
    </div>

    <div style="width: 100%;height: 60px">
        {{# if(d.orderState == 0 ){ }}
        {{# } else if(d.orderState == 1 ) { }}
        <button class="layui-btn layui-btn-sm layui-btn-normal" style="float: right;margin: 6px 10px;"
                onclick="sendProduct('{{d.orderId}}',true)">去发货
        </button>
        {{# } else if(d.orderState == 2 ) { }}
        {{# } else {}}
        {{# }}}
    </div>
</script>
<script>
    var userId = '${sessionScope.user.id}';
    //注意：导航 依赖 element 模块，否则无法进行功能性操作
    layui.use('element', function () {
        var element = layui.element;
    });

    let laytpl = null;
    layui.use('laytpl', function () {
        laytpl = layui.laytpl;
    });

    var layer = null;
    layui.use('layer', function () {
        layer = layui.layer;
        let backMessage = '${sessionScope.backMessage}';
        if (backMessage !== "") {
            backMessage = JSON.parse(backMessage);
            let icon = backMessage.success === true ? 1 : 2;
            layer.msg(backMessage.message, {
                icon: icon
                , time: 2000
            });
            <%
            session.removeAttribute("backMessage");
            %>
        }
    });

    var purchaseTable = null;
    var sellTable = null;
    layui.use('table', function () {
        var table = layui.table;

        //第一个实例
        purchaseTable = table.render({
            elem: '#table_purchase'
            , height: 410
            , cellMinWidth: 100
            , url: 'http://localhost/campus/person/orderList?userId=' + userId + '&isPurchase=true'//数据接口
            , page: {
                layout: ['count']
            } //开启分页
            , toolbar: true
            , defaultToolbar: [{
                title: '刷新'
                , layEvent: 'refresh'
                , icon: 'layui-icon-refresh-1'
            }, 'filter', 'exports', 'print',]
            , cols: [[ //表头
                {field: 'orderId', title: '订单号', width: '13%', align: 'center', sort: true, fixed: 'left'}
                , {field: 'productNames', title: '商品名', width: '13%', align: 'center'}
                , {field: 'totalPrice', title: '总价格', width: '10%', align: 'center', sort: true}
                , {
                    field: 'orderState', title: '状态', width: '10%', align: 'center'
                    , templet: "#purchaseOrderStateTpl"
                }
                , {field: 'purchaseTime', title: '购买时间', width: '11%', sort: true, align: 'center'}
                , {field: 'userName', title: '收件人', width: '11%', align: 'center'}
                , {field: 'phone', title: '联系电话', width: '11%', align: 'center'}
                , {field: 'address', title: '地址', width: '11%', align: 'center'}
                , {field: 'operation', title: '操作', width: '10%', align: 'center', templet: "#purchaseOperationTpl"}
            ]]
            , parseData: function (res) { //res 即为原始返回的数据
                return {
                    "code": res.code, //解析接口状态
                    "msg": res.message, //解析提示文本
                    "count": res.data.count, //解析数据长度
                    "data": res.data.item //解析数据列表
                };
            }
        });

        sellTable = table.render({
            elem: '#table_sell'
            , height: 410
            , cellMinWidth: 100
            , url: 'http://localhost/campus/person/orderList?userId=' + userId + '&isPurchase=false' //数据接口
            , page: {
                layout: ['count']
            }
            , toolbar: true
            , defaultToolbar: [{
                title: '刷新'
                , layEvent: 'refresh'
                , icon: 'layui-icon-refresh-1'
            }, 'filter', 'exports', 'print',]
            , cols: [[ //表头
                {field: 'orderId', title: '订单号', width: '13%', align: 'center', sort: true, fixed: 'left'}
                , {field: 'productNames', title: '商品名', width: '13%', align: 'center'}
                , {field: 'totalPrice', title: '总价格', width: '10%', align: 'center', sort: true}
                , {
                    field: 'orderState', title: '状态', width: '10%', align: 'center'
                    , templet: "#sellOrderStateTpl"
                }
                , {field: 'purchaseTime', title: '卖出时间', width: '11%', sort: true, align: 'center'}
                , {field: 'userName', title: '购买人', width: '11%', align: 'center'}
                , {field: 'phone', title: '联系电话', width: '11%', align: 'center'}
                , {field: 'address', title: '地址', width: '11%', align: 'center'}
                , {field: 'operation', title: '操作', width: '10%', align: 'center', templet: "#sellOperationTpl"}
            ]]
            , parseData: function (res) { //res 即为原始返回的数据
                return {
                    "code": res.code, //解析接口状态
                    "msg": res.message, //解析提示文本
                    "count": res.data.count, //解析数据长度
                    "data": res.data.item //解析数据列表
                };
            }
        });

        table.on('toolbar()', function (obj) {
            switch (obj.event) {
                case 'refresh':
                    purchaseTable.reload();
                    sellTable.reload();
                    break;
            }
            ;
        });

    });

    let orderDetailDialogIndex = 0;

    function orderDetail(data, isPurchase) {
        console.log(data);
        let getTpl = isPurchase ? purchaseOrderItemTpl.innerHTML : sellOrderItemTpl.innerHTML;
        let view = document.getElementById('orderDetailView');
        laytpl(getTpl).render(data, function (html) {
            view.innerHTML = html;
        });

        orderDetailDialogIndex = layer.open({
            type: 1
            , title: "详情信息"
            , area: '400px'
            , resize: false
            , tipsMore: true
            , content: $('#orderDetailView')
        });
    }

    function deleteOrder(orderId, which) {
        let warningMessage = "";
        let isBack = true;
        if (which === 1)
            warningMessage = "确定取消此订单?";
        else if (which === 2) {
            warningMessage = "确定删除此订单?";
            isBack = false;
        } else if (which === 3)
            warningMessage = "确定不卖了?";
        layer.confirm(warningMessage, {
            icon: 3
            , title: "提示"
        }, function (index) {
            //do something
            $.ajax({
                url: "http://localhost/campus/order/deleteOrder"
                , type: "POST"
                , data: "orderId=" + orderId + "&isBack=" + isBack
                , success: function (data) {
                    purchaseTable.reload();
                    sellTable.reload();
                    let icon = data.success ? 1 : 2;
                    layer.msg(data.message, {
                        icon: icon
                        , time: 2000
                    });
                }
                , error: function (e) {

                }
            });
            layer.close(index);
            layer.close(orderDetailDialogIndex);
        });
    }

    function paySuccess(orderId, payWay, qrcodeUrl) {
        if (payWay === "0") {
            layer.msg("订单已过期，请取消重新下单", {
                icon: 3
                , time: 2000
            });
        } else if (payWay === "1") {
            let length = $("#qrcode").children().length;
            if (length === 0) {
                generateQRCode("canvas", 200, 200, qrcodeUrl);
                setInterval(function () {
                    updateState(orderId)
                }, 1000);
            }
            layer.open({
                type: 1
                , title: "支付"
                , area: '400px'
                , resize: false
                , tipsMore: true
                , content: $('#qrcodeDiv')
            });
        }
    }

    function sendProduct(orderId, isSendProduct) {
        $.ajax({
            url: "http://localhost/campus/order/updateOrder"
            , type: "POST"
            , data: "orderId=" + orderId + "&isSendProduct=" + isSendProduct
            , success: function (data) {
                let icon = data.success ? 1 : 2;
                layer.msg(data.message, {
                    icon: icon
                    , time: 2000
                });
                purchaseTable.reload();
                sellTable.reload();
                layer.close(orderDetailDialogIndex);
            }
        });
    }

    function generateQRCode(renderMethod, picWidth, picHeight, url) {
        $("#qrcode").qrcode({
            render: renderMethod, // 渲染方式有table方式（IE兼容）和canvas方式
            width: picWidth, //宽度
            height: picHeight, //高度
            text: utf16to8(url), //内容
            typeNumber: -1,//计算模式
            correctLevel: 2,//二维码纠错级别
            background: "#ffffff",//背景颜色
            foreground: "#000000"  //二维码颜色
        });
    }

    //中文编码格式转换
    function utf16to8(str) {
        var out, i, len, c;
        out = "";
        len = str.length;
        for (i = 0; i < len; i++) {
            c = str.charCodeAt(i);
            if ((c >= 0x0001) && (c <= 0x007F)) {
                out += str.charAt(i);
            } else if (c > 0x07FF) {
                out += String.fromCharCode(0xE0 | ((c >> 12) & 0x0F));
                out += String.fromCharCode(0x80 | ((c >> 6) & 0x3F));
                out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
            } else {
                out += String.fromCharCode(0xC0 | ((c >> 6) & 0x1F));
                out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
            }
        }
        return out;
    }

    function updateState(orderId) {
        $.ajax({
            url: "http://localhost/campus/order/queryPayStatus/" + orderId
            , type: "GET"
            , success: function (res) {
                if (res.success && res.code != 25000) {
                    window.location.href = "http://localhost/campus/order/paySuccess?orderId=" + orderId
                } else {
                    $("#qrcode_warning").text(res.message);
                }
            }
        });
    }

</script>
</body>
</html>
